package jmine.tec.rpc.common.serialization.json;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import jmine.tec.json.JSON;
import jmine.tec.json.JSONObject;
import jmine.tec.json.JSONString;
import jmine.tec.rpc.RPCMessages;
import jmine.tec.rpc.common.RPCException;
import bancosys.tec.utils.date.Time;

/**
 * Conversor de JSON para Java e vice-versa
 * 
 * @author lundberg
 */
public class JSONTimeConverter extends AbstractJSONObjectConverter implements JSONConverterStrategy {

    /**
     * {@inheritDoc}
     */
    public boolean matchesJava(Object object) {
        return object instanceof Time;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected JSON objectType() {
        return new JSONString("time");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object instantiate(JSONConversionContext context, JSON json) {
        try {
            return new Time(this.dateFormat().parse(json.getProperty("value").toString()));
        } catch (ParseException e) {
            throw new RPCException(RPCMessages.INVALID_DATE_VALUE.create(json.getProperty("value")), e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillObject(JSONConversionContext context, JSON json, Object object) {
        // OK
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillJSON(JSONConversionContext context, Object object, JSONObject json) {
        json.setProperty("value", new JSONString(this.dateFormat().format((Time) object)));
    }

    /**
     * @return date format
     */
    private DateFormat dateFormat() {
        return new SimpleDateFormat("HH:mm:ss.SSSZ");
    }
}
